<template>
  <div class="mind-map-page" :class="{'mind-map-read':isRead}">
    <toolBar :isPrivew="isPrivew" :isReadOnly='isReadOnly' v-if="!isRead" :infoData="infoData" :docInfo="docInfo"></toolBar>
    <div class="mindMapContainer" ref="mindMapContainer"></div>
    <SidebarTrigger v-if="!isRead" :activeSidebar="activeSidebar"></SidebarTrigger>
    <OutlineSidebar v-if="!isRead&&mindMap" :activeSidebar="activeSidebar" :mindMap="mindMap"></OutlineSidebar>
    <Style v-if="!isRead" :activeSidebar="activeSidebar"></Style>
    <BaseStyle :data="mindMapData" :mindMap="mindMap" v-if="!isRead" :activeSidebar="activeSidebar"></BaseStyle>
    <Theme :mindMap="mindMap" v-if="!isRead" :activeSidebar="activeSidebar"></Theme>
    <Structure :mindMap="mindMap" v-if="!isRead" :activeSidebar="activeSidebar"></Structure>
    <ShortcutKey v-if="!isRead" :activeSidebar="activeSidebar"></ShortcutKey>
    <Contextmenu v-if="mindMap && !isRead" :mindMap="mindMap"></Contextmenu>
    <Count v-if="mindMap" :mindMap="mindMap" :class="{'mind-tool-abs':isRead}"></Count>
    <Navigator :mindMap="mindMap"></Navigator>
    <NavigatorToolbar :mindMap="mindMap" ref="navigatorToolbar" :class="{'mind-tool-abs':isRead}" :isRead="isRead"></NavigatorToolbar>
    <NodeIconSidebar v-if="mindMap&&!isRead" :mindMap="mindMap" :activeSidebar="activeSidebar"></NodeIconSidebar>
    <NodeIconToolbar v-if="mindMap&&!isRead" :mindMap="mindMap"></NodeIconToolbar>
    <formulaSiderbar v-if="mindMap&&!isRead" :mindMap="mindMap" :activeSidebar="activeSidebar"></formulaSiderbar>
    <NodeImgPreview v-if="mindMap&&!isRead" :mindMap="mindMap"></NodeImgPreview>
    <!-- <version ref="version" :isPrivew="isPrivew" @changePrivew="changePrivew" @endSwitchVersion="endSwitchVersion" :id="id"
      @saveVersion="saveVersion" :isMark="false"></version> -->
  </div>
</template>

<script setup lang="ts">
import {
  ref,
  reactive,
  toRefs,
  watch ,
  onMounted,
  getCurrentInstance,
  nextTick,
  onUnmounted,
  onBeforeUnmount,
} from 'vue' 
import type { ComponentInternalInstance } from 'vue'
import MindMaps from 'simple-mind-map'
import xmind from 'simple-mind-map/src/parse/xmind.js'
import MiniMap from 'simple-mind-map/src/plugins/MiniMap.js'
import Watermark from 'simple-mind-map/src/plugins/Watermark.js'
import KeyboardNavigation from 'simple-mind-map/src/plugins/KeyboardNavigation.js'
import ExportPDF from 'simple-mind-map/src/plugins/ExportPDF.js'
import ExportXMind from 'simple-mind-map/src/plugins/ExportXMind.js'
import Export from 'simple-mind-map/src/plugins/Export.js'
import Drag from 'simple-mind-map/src/plugins/Drag.js'
import Select from 'simple-mind-map/src/plugins/Select.js'
import RichText from 'simple-mind-map/src/plugins/RichText.js'
import AssociativeLine from 'simple-mind-map/src/plugins/AssociativeLine.js'
import TouchEvent from 'simple-mind-map/src/plugins/TouchEvent.js'
import NodeImgAdjust from 'simple-mind-map/src/plugins/NodeImgAdjust.js'
import SearchPlugin from 'simple-mind-map/src/plugins/Search.js'
import Painter from 'simple-mind-map/src/plugins/Painter.js'
import ScrollbarPlugin from 'simple-mind-map/src/plugins/Scrollbar.js'
import Formula from 'simple-mind-map/src/plugins/Formula.js'
import { useHookI18n } from '@/hooks/i18n'
const { locale,$t } = useHookI18n()
MindMaps.usePlugin(MiniMap)
  .usePlugin(Watermark)
  .usePlugin(Drag)
  .usePlugin(KeyboardNavigation)
  .usePlugin(ExportPDF)
  .usePlugin(ExportXMind)
  .usePlugin(Export)
  .usePlugin(Select)
  .usePlugin(AssociativeLine)
  .usePlugin(NodeImgAdjust)
  .usePlugin(TouchEvent)
  .usePlugin(SearchPlugin)
  .usePlugin(Painter)
  .usePlugin(Formula)
import toolBar from './toolbar.vue'
import OutlineSidebar from './OutlineSidebar.vue'
import BaseStyle from './BaseStyle.vue'
import Theme from './Theme.vue'
import Structure from './Structure.vue'
import ShortcutKey from './ShortcutKey.vue'
import Count from './Count.vue'
import Contextmenu from './Contextmenu.vue'
import NavigatorToolbar from './NavigatorToolbar.vue'
import Navigator from './Navigator.vue';
import Style from './Style.vue'
import SidebarTrigger from './SidebarTrigger.vue'
import formulaSiderbar from './FormulaSidebar.vue'
import NodeImgPreview from './NodeImgPreview.vue'
import NodeIconSidebar from './NodeIconSidebar.vue'
import NodeIconToolbar from './NodeIconToolbar.vue'
import exampleData from "./config/exampleData"
import { getShareInfo, preview, saveContent } from "@/api/common";
import { saveVersion } from '@/api/version'
import useCommonStore from '@/store/common'
import { useRouter } from "vue-router"
const instance: any = getCurrentInstance() as ComponentInternalInstance;
const proxy: any = instance.proxy as any; // 访问 proxy 属性
const commonStore = useCommonStore();
const router = useRouter();
const emit = defineEmits(["renderFinish",'changeLatelySave','changePrivew'])
const props = defineProps({
  id:{
      type: String,
      default: () => {
        return ''
      },
    },
    formShare: {
      type: Boolean
    },
    isPrivew:{
      type:Boolean,
      default:false
    },
    // 是否只读
    isRead: {
      type: Boolean,
      default: () => {
        return false
      },
    },
    isReadOnly:{
      type: Boolean,
      default: () => {
        return false
      },
    },
    infoData:{
      type:Object,
      default(){
        return {}
      }
    },
    docInfo:{
      type:Object,
      default(){
        return {}
      }
    }
})
const mindMapData = ref({})
const mindMap = ref()
const allContent = ref('')
const content = ref('')
const mindMapContainer = ref()
const useLeftKeySelectionRightKeyDrag = ref(false)
const addEvent = ref(false)
const activeSidebar = ref('')
watch(()=>props.isPrivew,(newVal,oldVal)=>{
  if(newVal!=oldVal){
    mindMap.value.setMode(newVal ? 'readonly' : 'edit')
  }
},{
  deep:true
})
watch(()=>props.id,(newVal,oldVal)=>{
  getData()
},{
  deep:true
})

onMounted(()=>{
  nextTick(()=>{
    getData()
    proxy.$eventBus.$on('execCommand', execCommand)
     // 修改导出内边距
    proxy.$eventBus.$on('paddingChange', onPaddingChange)
    proxy.$eventBus.$on('xmindEport', xmindEport)
    proxy.$eventBus.$on('setData', setData)
    proxy.$eventBus.$on('startTextEdit', handleStartTextEdit)
    proxy.$eventBus.$on('endTextEdit', handleEndTextEdit)
    proxy.$eventBus.$on('createAssociativeLine', handleCreateLineFromActiveNode)
    proxy.$eventBus.$on('startPainter', handleStartPainter)
    proxy.$eventBus.$on('changeSidebar', changeActiveSidebar)
    // proxy.$eventBus.$on('node_tree_render_end', handleHideLoading)
    // proxy.$eventBus.$on('showLoading', handleShowLoading)
  })
})
onBeforeUnmount(()=>{
  proxy.$eventBus.$off('execCommand', execCommand)
     // 修改导出内边距
  proxy.$eventBus.$off('paddingChange', onPaddingChange)
  proxy.$eventBus.$off('xmindEport', xmindEport)
  proxy.$eventBus.$off('setData', setData)
  proxy.$eventBus.$off('startTextEdit', handleStartTextEdit)
  proxy.$eventBus.$off('endTextEdit', handleEndTextEdit)
  proxy.$eventBus.$off('createAssociativeLine', handleCreateLineFromActiveNode)
  proxy.$eventBus.$off('startPainter', handleStartPainter)
  proxy.$eventBus.$off('changeSidebar', changeActiveSidebar)
  mindMap.value?.destroy()
})
function changeActiveSidebar(val){
  activeSidebar.value = val
}
function execCommand(...args) {
  mindMap.value.execCommand(...args)
}
async function xmindEport(...args) {
  // try {
  //   showLoading()
  //   await mindMap.value.export(...args)
  //   hideLoading()
  // } catch (error) {
  //   console.log(error)
  //   hideLoading()
  // }
  let callBack = args[args.length-1]
  try {
    await mindMap.value.export(...args)
    if(typeof callBack == 'function'){
        callBack()
    }
  } catch (error) {
    console.log(error)
  }
}
function handleStartTextEdit(){
  mindMap.value.renderer.startTextEdit();
}
function handleEndTextEdit() {
  mindMap.value.renderer.endTextEdit()
}
// 修改导出内边距
function  onPaddingChange(data) {
  mindMap.value.updateConfig(data)
}
function handleCreateLineFromActiveNode() {
  mindMap.value.associativeLine.createLineFromActiveNode()
}
function handleStartPainter() {
  mindMap.value.painter.startPainter()
}
function getData(){
  mindMapData.value = JSON.parse(JSON.stringify(exampleData))
  let fun = preview
  if(props.formShare) {
    fun = getShareInfo
  }
  fun(props.id).then(async res=>{
    if (res.data.code == 0 && res.data.data) {
      if (res.data.data.content && res.data.data.content.startsWith("{")) {
        let contentObj = JSON.parse(res.data.data.content)
        mindMapData.value = JSON.parse(contentObj.content)
      } else if(res.data.data.content && res.data.data.content.startsWith("[")){
        allContent.value = await xmind.transformXmind(res.data.data.content)
        mindMapData.value.root = allContent.value
      }else{
        content.value = "";
        mindMapData.value.root = {
          children:[],
          data:{
            text:$t('message.text.rootNode'),
            expand: true,
            isActive: false
          }
        }
      }
      nextTick(()=>{
        if(!mindMap.value){
          setInitEditor()
        }else{
          mindMap.value.view.reset()
          // this.$refs.navigatorToolbar.setScale(1)
          setData(mindMapData.value)
        }
      })
    }
  }).catch(err=>{
  })
}
function setInitEditor(){
  let { root, layout, theme, view, config } = mindMapData.value
  mindMap.value = new MindMaps({
    el: mindMapContainer.value,
    data: root,
    fit: false,
    layout: layout,
    theme: theme.template,
    themeConfig: theme.config,
    viewData: view,
    nodeTextEditZIndex: 1000,
    nodeNoteTooltipZIndex: 1000,
    customNoteContentShow: {
      click:(value, left, top, node)=>{
      },
      show:(value, left, top, node)=>{
        if(!addEvent.value){
          addEvent.value = true
        }
      },
      hide:()=>{
        if(addEvent.value){
          addEvent.value = false
        }
      }
    },
    ...(config || {}),
    useLeftKeySelectionRightKeyDrag:useLeftKeySelectionRightKeyDrag.value,
    initRootNodePosition: ['center', 'center'],
    customInnerElsAppendTo: null,
    enableAutoEnterTextEditWhenKeydown: true,
  })
  // // 保存
  // mindMap.value.keyCommand.addShortcut('Control+s', () => {
  // })
  // 转发事件
  ;[
  'node_active',
  'data_change',
  'view_data_change',
  'back_forward',
  'node_contextmenu',
  'node_click',
  'draw_click',
  'expand_btn_click',
  'svg_mousedown',
  'mouseup',
  'mode_change',
  'node_tree_render_end',
  'rich_text_selection_change',
  'transforming-dom-to-images',
  'generalization_node_contextmenu',
  'painter_start',
  'painter_end',
  'scrollbar_change',
  'scale'
  ].forEach((event) => {
    mindMap.value.on(event, (...args) => {
      if(event=='node_click'&&addEvent.value){
        proxy.$eventBus.$emit('showNodeNote',true)
      }else{
        proxy.$eventBus.$emit(event, ...args)
      }
    })
  })
  if(props.isRead){
    mindMap.value.keyCommand.pause()
    mindMap.value.setMode('readonly')
  }
  addRichTextPlugin()
  emit('renderFinish')
}
function setData(data) {
  if (data.root) {
    mindMap.value.setFullData(data)
  } else {
    mindMap.value.setData(data)
  }
  emit('renderFinish')
}
function addRichTextPlugin() {
  if (!mindMap.value) return
  mindMap.value.addPlugin(RichText)
}
function closeShortKey(val){
  // if(val){
  //   mindMap.value.keyCommand.pause()
  // }else{
  //   mindMap.value.keyCommand.recovery()
  // }
}
function  changeEditStatus(val){
  if(val){
    mindMap.value.setMode('readonly')
  }else{
    mindMap.value.setMode('edit')
  }
}
function handleSave(){
  let dataObj = mindMap.value.getData(true)
  // let otherObj = {
  //   layout:dataObj.layout,
  //   theme:dataObj.theme,
  //   view:dataObj.view
  // }
  let fun = saveContent
  fun(props.id, { content: JSON.stringify(dataObj)}).then( res => {
    if (res.data.code == 0) {
      proxy.$notify({
        title: $t('message.message.saveSuccess'),
        type: "success",
        position: "bottom-right",
      });
      emit("changeLatelySave",new Date())
    }
  });
}
function saveVersionFun(){
  let dataObj = mindMap.value.getData(true)
  saveVersion({
    dcId:props.id,
    content:JSON.stringify(dataObj)
  }).then(res=>{
    if(res.data.code == 0){
      proxy.$notify({
        title: $t('message.message.generatedVersionSuccess'),
        type: "success",
        position: "bottom-right",
      });
    }
  })
}
function downFile(item,downType){
  let storeDownItem = {
    id:item.id,
    name:item.name,
    isFinish:false,
    downTime:new Date().getTime()
  }
  let soteDownList = commonStore.downFileList
  soteDownList.push(storeDownItem)
  commonStore.setDownLoadFileList(soteDownList)
  xmindEport(downType,true,item.name,downType=='svg'?`* {
                            margin: 0;
                            padding: 0;
                            box-sizing: border-box;
                        }`:true,()=>{
    soteDownList.forEach((item)=>{
      if(item.downTime==storeDownItem.downTime){
        item.isFinish = true
      }
    })
    commonStore.setDownLoadFileList(soteDownList)
    proxy.$notify({
      message:$t('message.message.downloadSuccess'),
      title: $t('message.buttons.download'),
      type: "success",
      position: "bottom-right",
    });
  })
}
function changePrivew(){
  emit('changePrivew',!props.isPrivew)
}
function changeVersionContent(content,type){
  if(type=='handleVersion'){
    content.value = JSON.parse(content)
    setData(content.value)
  }
}
defineExpose({
  closeShortKey,
  handleSave,
  saveVersionFun,
  changeEditStatus,
  changeVersionContent,
  downFile
})
</script>
<style lang="scss" scoped>
.mind-map-page{
  height: 100%;
  width: 100%;
  .mindMapContainer{
    height: 100%;
    width: 100%;
    ::v-deep(p){
      margin: 0px !important;
      padding: 0px !important;
    }
  }
  ::v-deep(.mindMapContainer svg){
    width: 100% !important;
  }
}
.mind-map-read{
  position: relative;
  height: calc(100vh - 200px);
}
.mind-tool-abs{
  position: absolute;
}
</style>
<!-- <style ang="scss">
.mindMapContainer{
    ::v-deep(p){
      margin: 0px !important;
      padding: 0px !important;
    }
  }
</style> -->